<?php

/*
 * $Id: collection.php 12 2010-11-28 20:02:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-28 20:02:53 +0000 (Sun, 28 Nov 2010) $
 * $Revision: 12 $
 */

namespace cmFly\system\data_model\orm;

abstract class collection extends base {

    public static function __callStatic($name, $arguments) {
	if (substr($name, 0, 7) == 'get_by_') {
	    $result = FALSE;
	    if (\method_exists(get_called_class(), $name)) {
		$result = \call_user_func_array(\get_called_class() . '::' . $name, $arguments);
	    } else {
		$by = explode('_', substr($name, 7));
		if (empty($by) || empty($by[0])) {
		    throw new data_model\exception(\get_called_class() . '::get_by method must be specify field or index!');
		}
		switch ($by[0]) {
		    default:
			$select = static::get_select();
			$where = '';
			for ($i = 0; $i < count($by); $i+=2) {
			    $where.=$by[$i] . ' = ?';
			    if (isset($by[$i + 1])) {
				$where.=' ' . $by[$i + 1] . ' ';
			    }
			}
			$result = $select->where($where, $arguments);
			if (!$result) {
			    throw new data_model\exception('Internal error! result in __callStatic is empty!');
			}

			$statement = $result->query();
			$count = $statement->rowCount();
			$model = static::parse_row($statement);
			return $model;
		}
		throw new data_model\exception('Call to undefined or protected function "' . \get_called_class() . '::' . $name . '"');
	    }
	}
    }

    public function clean() {

    }
}

